﻿using Avalonia.Media.Imaging;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using OpenCvSharp;
using Share.Core.Events;
using Share.Core.Utils;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace SidebarStarted.ViewModels.OpenCvSharp;

/// <summary>
/// OpenCvSharp  实现证件照
/// </summary>
public partial class IdentityPhotoPageViewModel : ViewModelBase
{
    private readonly IMessageService _messageService;

    public IdentityPhotoPageViewModel()
    {
        _messageService = new MessageService();
    }

    /// <summary>
    /// 预览图
    /// </summary>
    [ObservableProperty]
    private Bitmap _previewBitmap;

    /// <summary>
    /// 结果图
    /// </summary>
    [ObservableProperty]
    private Bitmap _resultBitmap;

    /// <summary>
    /// 选择地址
    /// </summary>
    [ObservableProperty]
    private string _selectImagePath;

    /// <summary>
    /// 选择文件
    /// </summary>
    [RelayCommand]
    private async Task SelectFilesAsync()
    {
        var selectFileList = await DialogHelper.OpenFileDialogAsync(this, "请选择文件", false);
        if (!selectFileList.Any())
        {
            _messageService.SendMessage("请选择文件");
            return;
        }

        SelectImagePath = selectFileList.First();
        var fileInfo = new FileInfo(SelectImagePath);

        // 检查是否为图片文件
        if (IsImageFile(fileInfo))
        {
            // 读取并转换为IBitmap
            var path = selectFileList.First();
            await using var stream = File.OpenRead(path);

            // 将stream转换为Bitmap
            PreviewBitmap = new Bitmap(stream);
        }
        else
        {
            // 处理非图片文件的情况（例如清除预览或显示错误提示）
            _messageService.SendMessage("文件格式不对");
        }
    }

    /// <summary>
    /// 图片处理
    /// </summary>
    [RelayCommand]
    private void Handler()
    {
        if (!File.Exists(SelectImagePath))
        {
            _messageService.SendMessage("图片未找到");
            return;
        }

        //读取照片
        var img = Cv2.ImRead(SelectImagePath);
        Cv2.ImShow("原图.png", img);

        //图像缩放
        //Mat mg = new Mat();
        //Cv2.Resize(img, mg, new Size(200,200), 0.5, 0.5);
        //Cv2.ImShow("mg.png", mg);

        //图片转换为灰度图
        var hsv = new Mat();
        Cv2.CvtColor(img, hsv, ColorConversionCodes.BGR2HSV);
        Cv2.ImShow("hsv.png", hsv);

        //图片的二值化处理
        Mat mask = new Mat();
        Scalar lower_blue = new Scalar(90, 70, 70);
        Scalar upper_blue = new Scalar(110, 255, 255);
        Cv2.InRange(hsv, lower_blue, upper_blue, mask);
        Cv2.ImShow("mask.png", mask);

        //腐蚀膨胀
        Mat erode = new Mat();
        Cv2.Erode(mask, erode, 1);

        Mat dilate = new Mat();
        Cv2.Erode(erode, dilate, 1);
        Cv2.ImShow("dilate.png", dilate);

        for (var r = 0; r < img.Rows; r++)
        {
            for (var c = 0; c < img.Cols; c++)
            {
                if (dilate.At<byte>(r, c) == 255)
                {
                    var vec3B = dilate.At<Vec3b>(r, c);

                    //此处替换颜色，为BGR通道，不是RGB通道
                    vec3B.Item0 = 255;
                    vec3B.Item1 = 255;
                    vec3B.Item2 = 255;

                    img.Set(r, c, vec3B);
                }
            }
        }

        Cv2.ImShow("白底.png", img);

        //窗口等待的命令，0表示无限等待
        //Cv2.WaitKey(0);
    }

    private bool IsImageFile(FileSystemInfo fileInfo)
    {
        // 根据文件扩展名判断是否为图片文件，例如：
        return new[]
               {
                   ".jpg",
                   ".jpeg",
                   ".png",
                   ".bmp",
                   ".gif"
               }.Contains(fileInfo.Extension.ToLower());
    }
}